
<?php
require_once(dirname(__FILE__).'/../include/config.inc.php');
require_once(dirname(__FILE__).'/../include/mysqli.class.php');

class order{
	public $db;
	public $config;
	public function __construct($db,$config){
		$this->db=$db;
		$this->config=$config;
    }

    //确认收货
	public function confirmOrder($oid){
        if (empty($oid)) jsonError('订单信息异常');
        $orderInfo = $this->db->GetOne('select a.*,b.merchant_num,b.merchant_key from dyspw_goods_order as a inner join dyspw_member as b on a.shop_id = b.id where a.id = '.$oid.' and b.is_vip = 3');
        if(!$orderInfo) jsonError('订单信息不存在');
		//添加导购员销量信息
		if($orderInfo['guide_uid'] != 0 && !empty($orderInfo['guide_uid'])){
			$guide = $this->db->GetOne("select * from dyspw_shop_guide where guide_id = {$orderInfo['guide_uid']}");
			if(!empty($guide)){
				$this->db->ExecNoneQuery("Update dyspw_shop_guide set guide_money = guide_money + {$orderInfo['money']} where guide_id = {$orderInfo['guide_uid']}");
			}
		}
        $sharing_state=1;
        //存在问题  订单的派送状态未验证
        //参与分账的订单
		if($orderInfo['profit_sharing'] == 'Y'){
            //是否参与过分账并且成功
			if($orderInfo['sharing_state'] == '1'){
                //账号绑定商户号
                if($orderInfo['merchant_num']){
                    $orderCode=time().mt_rand(1000,9999);
                    $money=$orderInfo['money'];
                    $delivery_fee=$orderInfo['delivery_fee'] ? $orderInfo['delivery_fee'] : 0;
					 $wxPayment=new wxPayment($this->config);
                     $result=$wxPayment->profitShare([
                         'sub_mch_id'=>$orderInfo['merchant_num'],//特约商户号
                         'transaction_id'=>$orderInfo['transaction_id'],
                         'out_order_no'=>$orderCode,
                         'receivers'=>[
                             ['type'=>'MERCHANT_ID',  'account'=>$this->config['mchId'],  "amount"=>intval($money*0.03 + $delivery_fee),"description"=>"分到服务商"]
                         ]
                     ]);
                    //分账状态
                    $sharing_state=$result['status'] ? 0 : 2;
                    $remark=json_encode($result['data'],JSON_UNESCAPED_UNICODE);
                    //记录分账日志
					$order_id = $sharing_state ? '' : $result['data']['order_id'];
                    $print_sql="INSERT INTO separate_log(oid,money,create_time,out_order_no,order_id,status,remark) VALUES('$oid','$money',".time().",
'$orderCode','$order_id','$sharing_state','$remark') ON DUPLICATE KEY UPDATE money='$money',out_order_no='$orderCode',order_id='$order_id',status='$sharing_state',create_time = ".time().",remark = '$remark'";
                    if(!$this->db->ExecNoneQuery($print_sql)) jsonError('日志记录异常');
                }
			}
		}
		//更新订单状态
		if(!$this->db->ExecNoneQuery('update dyspw_goods_order set state = 3 and  sharing_state ='.$sharing_state)) jsonError('确认收货异常');
		jsonSuccess();
    }


    /*
     * 获取商户外卖分类信息
     */
    public function merchantType($id){
        if (empty($id)) jsonError('商户信息异常');
        $merchantInfo = $this->db->GetOne('select industry_type,sort from dyspw_member  where id = '.$id.' and is_vip = 3');
        if(!$merchantInfo) jsonError('商户信息不存在');
        $data=[];
        if($merchantInfo['sort'] == '92'){
            //外卖性质
            if(!$merchantInfo['industry_type']) jsonError('商户未绑定外卖行业');
            $this->db->Execute("select id,classname from dyspw_takeaway where parentid = ".$merchantInfo['industry_type']);
            while($merchant = $this->db->GetArray()){
                $data[]=$merchant;
            }
            if(!$data) jsonError('请先添加外卖行业分类');
        }
        jsonSuccess($data);
    }

    /*
     * 获取外卖购物车商品支付信息
     */

    public function goodList($shopId,$goods){
        //商铺是否是外卖性质，并且设置里营业属性
        $merchantInfo = $this->db->GetOne('select a.avatar,a.username,a.id as shop_id,a.merchant_num,a.industry_type,b.id,b.shop_name,b.shop_lat,b.pack_fee,b
.delivery_fee,b.state,b.start_time,b.end_time from dyspw_member as a LEFT JOIN dyspw_shop_waimai as b on a.id = b.uid where a.id = ' .$shopId.' and a.is_vip = 3 and a.sort = 92');
        if(!($merchantInfo && $merchantInfo['industry_type']))  jsonError('商户信息不存在');
        if(!$merchantInfo['state']) jsonError('此商户不支持外卖配送');
        if(!$position=array_filter(explode(',',$merchantInfo['shop_lat']))) jsonError('商户位置信息不准确');
        //商户经营时间范围
        $start_time=strtotime(date('Y-m-d',time()).($merchantInfo['start_time'] ?  $merchantInfo['start_time'].':00' : '08:00:00'));
        $end_time=strtotime(date('Y-m-d',time()).($merchantInfo['end_time'] ?  $merchantInfo['end_time'].':59' : '21:59:59'));
        if(!(time()>$start_time && time()<$end_time)) jsonError('商户已打烊');
        //外卖商户商品信息
        $goods=json_decode($goods,true);
        if(!$goods) jsonError('请添加商品');
        $goods=array_column($goods,NULL,'gid');
        $gid=implode(',',array_column($goods,'gid'));
        $this->db->Execute("select id,title,money,img,details from dyspw_goods where u_id = ".$shopId." and id in (".$gid.")");
        $data=[];
        while($merchant = $this->db->GetArray()){
            $data[]=$merchant;
        }
        $money=0;
        foreach ($data as $k=>$v){
            $money += $goods[$v['id']]['num']*$v['money'];
            $data[$k]['num']=$goods[$v['id']]['num'];
        }
        if(isset($_GET['payStatus'])){
            self::payPrepay($money,$merchantInfo,$data);
        }
        $money =number_format(($money+$merchantInfo['pack_fee']),2);
        $return_data=[
            'shopname'=>$merchantInfo['shop_name'],
            'goods'=>$data,
            'pack_fee'=>$merchantInfo['pack_fee'],
            'delivery_fee'=>$merchantInfo['delivery_fee'],
            'money'=>$money,
            'total_money'=>$money+$merchantInfo['delivery_fee'],
            'ssw_id'=>$merchantInfo['id']
        ];
        jsonSuccess($return_data);
    }

    /*
     * 外卖订单支付
     */
    public function payPrepay($money,$merchant,$goods){
        $Totalprice=number_format(($money+$_POST['deliveryFree']+$merchant['pack_fee']),2);
        $wxPayment= new wxPayment($this->config);
        $orderCode=time().mt_rand(1000,9999);
        $uid=$_POST['uid'];
        $order_details=json_encode($goods,JSON_UNESCAPED_UNICODE);
        $param=[
            'body'=>'吉事多',
            'out_trade_no'=>$orderCode,
            'total_fee'=> $Totalprice*100,
//            'total_fee'=>1,
            'notify_url'=>'http://5p8.fyh5p8.com/xiaochengxu/WxPay_back.php',
            'trade_type'=>'JSAPI',
            'openid'=> $_POST['openid']
        ];
        //商户号是否绑定 订单是否分账
        $profit_sharing='N';
        if($merchant['merchant_num']){
            $profit_sharing=$param['profit_sharing']='Y';
            $param['sub_mch_id']=$merchant['merchant_num'];
        }
        $goods_id=$goods[0]['id'];
        //数据库写入订单信息
        $sql = "INSERT INTO dyspw_goods_order(goods_id,u_id, shop_id, money,remarks, time,u_avatar,u_name,ordernum,add_id,meal_num,mobile_is,waimai_id,order_type,profit_sharing,pack_fee,delivery_fee,Totalprice,order_details) VALUES ('{$goods_id}','{$uid}','{$merchant['shop_id']}','{$money}','{$_POST['remarks']}',".time().",'{$merchant['avatar']}','{$merchant['username']}','{$orderCode}','{$_POST['add_id']}','{$_POST['meal_num']}','false','{$merchant['id']}','waimai','{$profit_sharing}','{$merchant['pack_fee']}','{$_POST['deliveryFree']}','{$Totalprice}','{$order_details}')";
        if(!$this->db->ExecNoneQuery($sql))  jsonError('订单创建失败');
        $result=$wxPayment->paymentProvider($param);
        if($result['status'])  jsonSuccess($result['data']);
        jsonError($result['data']);
    }

    /*
     * 定时上传视频
     */
    public function uploadVideo(){
        $this->db->Execute("SELECT a.webnote,a.linkurl FROM dyspw_weblink a JOIN (SELECT RAND() * (SELECT MAX(id) FROM dyspw_weblink) AS nid) b ON a.id > b.nid LIMIT 2");
        $data='';
        while($info = $this->db->GetArray()){
            $data .= '(93,0,"xYasin","'.$info['webnote'].'","'.$info['linkurl'].'",'.time().',591,320500,"苏州市",1),';
        }
        $sql='INSERT INTO dyspw_weblink(classid,parentid,webname,webnote,linkurl,posttime,u_id,address_id,address_name,is_vip) VALUES'.rtrim($data,',');
        jsonSuccess($sql);
        if(!$this->db->ExecNoneQuery($sql))  jsonError();
        jsonSuccess();
    }

    /*
     * 长连接拉取订单
     */
    public function orderMessage($file_path){
        header('X-Accel-Buffering: no');
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        while (1) {
            if(file_get_contents($file_path)){
                echo "data: true\n\n";
            }else{
                echo "data: false\n\n";
            }
            ob_end_flush();
            flush();
            sleep(3);
        }
    }


    /*
     * 获取打印模板
     */
    public function printTpl($file_path){
        $fp = fopen($file_path, 'r');
        if ($fp == false) {
            jsonError('模板文件无法打开');
        }
        $str = fread($fp, filesize($file_path));
        jsonSuccess(base64_encode($str));
    }

}
if(!isset($_GET['action'])) jsonError('非法请求');
$action=$_GET['action'];
$order=new order($dosql,$globalConfig['wx']);
switch ($action){
	case 'confirmOrder':
        if(!isset($_POST['id'])) jsonError('非法请求');
		$order->confirmOrder($_POST['id']);
		break;
    case 'merchantType':
        if(!isset($_POST['id'])) jsonError('非法请求');
        $order->merchantType($_POST['id']);
        break;
    case 'goodList':
        if(!isset($_POST['shop_id'])) jsonError('非法请求');
        if(!isset($_POST['goods'])) jsonError('非法请求');
        $order->goodList($_POST['shop_id'],$_POST['goods']);
        break;
    case 'uploadVideo':
        $order->uploadVideo();
        break;
    case 'orderMessage':
        $order->orderMessage($globalConfig['orderTips']);
        break;
    case 'printTpl':
        $order->printTpl($globalConfig['printTpl']);
        break;
	default :
		jsonError('非法请求');
		break;
}



?>
